<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="农场名称" prop="name">
        <el-select
          v-model="farmTourValue"
          placeholder="请选择农场" 
          class="!w-240px" 
          style="margin-right: 10px;"
          @change="handleFarmChange"
        >
          <el-option
            v-for="item in farmTourList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="queryParams.farmHouseId"
          placeholder="请选择农舍"
          clearable
          class="!w-240px"
          @change="handleHouseChange"
        >
          <el-option
            v-for="house in houseList" 
            :key="house.id"
            :label="house.houseName"
            :value="house.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" type="index" align="center" key="id" prop="id" width="60"/>
      <el-table-column label="农场名称" align="center" prop="farmId" />
      <el-table-column label="农舍名称" align="center" prop="farmHouseName" />
      <el-table-column label="设备Id" align="center" prop="deviceId" />
      <el-table-column label="告警信息" align="center" prop="faultMsg" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="持续时长" align="center" prop="continue">
         <template #default="scope">
          <span>
            {{ calculateDuration(scope.row.startTime, scope.row.endTime) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
    />
  </ContentWrap>

</template>

<script setup lang="ts">
import { debounce } from 'lodash';
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AreaApi, AreaVO } from '@/api/farm/farmArea'
import { FarmTourApi, FarmTourVO } from '@/api/farmTour/index';
import { FarmWarnApi, FarmWarnApiVO } from '@/api/farmTour/warn/index';

defineOptions({ name: 'Warn' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AreaVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

const farmTourValue = ref<any>(null) // 默认农场
const farmId = ref<number>(0)
const farmTourList = ref<FarmTourVO[]>([]); // 农场列表
const houseList = ref<any[]>([]); // 存储农舍列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  farmId:undefined,
  farmHouseName:undefined,
  farmHouseId:undefined,
  deviceId: undefined,
  faultMsg: undefined,
  startTime:undefined,
  timeRange:[],
  continue:undefined,
  detail:undefined,
  remark: undefined
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 持续时间换算
const calculateDuration = (startTime: number, endTime: number) => {
  if (!startTime || !endTime) return '未定义';
  const duration = endTime - startTime;
  if (duration < 0) return '无效时间';
  // const hours = Math.floor(duration / (1000 * 60 * 60));
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((duration % (1000 * 60)) / 1000);

  return `${minutes}分钟 ${seconds}秒`;
};

// 获取下拉农场列表
const getList = async () => {
  const res = await FarmTourApi.getFarmTour()
  if (res) {
    farmTourList.value = res
    // 设置默认选择为第一个农场
    if (farmTourList.value.length > 0) {
      farmTourValue.value = farmTourList.value[0].id; // 默认的农场
      await getHouseList(farmTourValue.value); // 获取农舍
    }
  } 
}

// 根据农场ID获取农舍列表
const getHouseList = async (selectedFarmID) => {
  const res = await FarmWarnApi.getFarmHouseApi({ farmId: selectedFarmID });
  if (res) {
    houseList.value = res;
    // 默认选择第一个农舍
    if (houseList.value.length > 0) {
      queryParams.farmHouseId = houseList.value[0].id; // 默认农舍
      await getWarn(queryParams.farmHouseId);
    } else {
      queryParams.farmHouseId  = undefined; // 如果没有农舍，清空选择
    }
  }
};
// 获取告警总览
const getWarn = async (farmHouseId:any =queryParams.farmHouseId) => {
  loading.value = true;
  const params = {
    farmId: farmTourValue.value,//农场ID
    farmHouseId:farmHouseId || queryParams.farmHouseId, // 传入的农舍ID
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    createTime: queryParams.timeRange.length === 2 ? queryParams.timeRange : undefined // 时间范围
  };
  try{
    const data = await FarmWarnApi.getAllWarnApi(params);
    if(data && data.list.length > 0){
      // 1.根据农场id来查找农场名称
      list.value = data.list.map(item => ({
        ...item,
        farmId: farmTourList.value.find(farm => farm.id === item.farmId)?.name || '未知农场'
      }));
      total.value = data.total;
    }else{
      list.value = [];
    }
  }catch(error){
    console.log(error,'error');
    list.value = [];
  }finally{
    loading.value = false;
  }
};

const handleFarmChange = async (selectedFarmID) => {
  houseList.value = [];
  queryParams.farmHouseId = undefined; // 清空农舍选择
  await getHouseList(selectedFarmID); // 获取新的农舍列表
  // 选择农场后立即获取当前选定农舍的告警信息
  if (houseList.value.length > 0) {
    queryParams.farmHouseId = houseList.value[0].id; // 默认选择第一个农舍
  }
  await getWarn(queryParams.farmHouseId); // 获取告警信息
};

// 切换农舍
const handleHouseChange = async (selectedHouseID) => {
  console.log(selectedHouseID,'selectedHouseID农舍');
  queryParams.farmHouseId = selectedHouseID;
  await getWarn(selectedHouseID);
};
/** 搜索按钮操作 */
const handleQuery =async () => {
  queryParams.pageNo = 1;
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields(); // 重置表单
  farmTourValue.value = farmTourList.value.length > 0 ? farmTourList.value[0].id : null; // 重新选择第一个农场
  if (farmTourValue.value) {
    getHouseList(farmTourValue.value).then(() => {
      queryParams.farmHouseId = houseList.value.length > 0 ? houseList.value[0].id : null; // 选择第一个农舍
      getWarn(queryParams.farmHouseId); // 获取告警信息
    });
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AreaApi.deleteArea(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
watch(() => queryParams.pageNo, async () => {
  await getWarn(queryParams.farmHouseId); // 根据当前选择的农舍获取数据
});

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
</style>